import 'package:app_updater/entity/download_record.dart';
import 'package:app_updater/entity/download_status.dart';
import 'package:app_updater/entity/installation_record.dart';
import 'package:app_updater_example/model/app_upgrade.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../controller/updater_controller.dart';
import 'business_dialog.dart';
import 'updater_bar.dart';

class AppUpdaterDialog extends StatefulWidget {
  const AppUpdaterDialog({Key? key, required this.upgrade}) : super(key: key);

  final AppUpgrade upgrade;

  @override
  State<AppUpdaterDialog> createState() => _AppUpdaterDialogState();
}

class _AppUpdaterDialogState extends State<AppUpdaterDialog> {
  final AppUpdaterController _controller = AppUpdaterController();

  @override
  Widget build(BuildContext context) {
    return AppBusinessDialog(
      image: const AssetImage('assets/images/header_update.png'),
      title: Text('发现新版本${widget.upgrade.androidVersion}'),
      body: Text('${widget.upgrade.androidDesc}'),
      bottom: GetBuilder<AppUpdaterController>(
        init: _controller,
        global: false,
        builder: _buildBottom,
      ),
    );
  }

  Widget _buildBottom(AppUpdaterController controller) {
    if (controller.isInitialized.isFalse) {
      return const CupertinoActivityIndicator();
    }

    final DownloadRecord? downloadRecord = controller.downloadRecord.value;
    final DownloadStatus? downloadStatus = controller.downloadStatus.value;
    final InstallationRecord? installRecord = controller.installRecord.value;

    if (downloadRecord != null &&
        downloadRecord.version == widget.upgrade.androidVersion &&
        downloadStatus != null &&
        (!downloadStatus.isDone || !downloadStatus.isFailed)) {
      if (downloadStatus.isDone) {
        return _buildInstallButton(context, downloadStatus, installRecord);
      }

      return _buildDownloadingProgress(context, downloadStatus);
    }

    // 尚未下载该版本APK
    return _buildDownloadButton(context);
  }

  Widget _buildDownloadButton(BuildContext context) {
    return ElevatedButton(
      onPressed: _onDownloadPressed,
      child: const Text(
        '立即更新',
        style: TextStyle(
          fontSize: 16,
          height: 22.5 / 16,
        ),
      ),
    );
  }

  Widget _buildDownloadingProgress(
    BuildContext context,
    DownloadStatus downloadStatus,
  ) {
    return AppUpdaterProgressBar(progress: downloadStatus.progress);
  }

  Widget _buildInstallButton(
    BuildContext context,
    DownloadStatus downloadStatus,
    InstallationRecord? installRecord,
  ) {
    final ThemeData theme = Theme.of(context);

    final bool isRetry = installRecord != null &&
        installRecord.toVersion == widget.upgrade.androidVersion;
    final String buttonText = isRetry ? '重新安装' : '安装';

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        if (isRetry) ...<Widget>[
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
                color: theme.errorColor.withOpacity(0.08),
                borderRadius: const BorderRadius.all(Radius.circular(4))),
            child: Text(
              '*安装时遇到问题？先关闭网络 -> 再次尝试安装 -> 安装完成后重新打开网络',
              style: TextStyle(
                color: theme.errorColor,
                fontSize: 10,
                height: 14 / 10,
              ),
            ),
          ),
          const SizedBox(height: 10),
        ],
        ElevatedButton(
          onPressed: _onInstallPressed,
          child: Text(
            buttonText,
            style: const TextStyle(
              fontSize: 16,
              height: 22.5 / 16,
            ),
          ),
        ),
        const SizedBox(height: 10),
        TextButton(
          onPressed: _onDownloadPressed,
          child: const Text('重新下载'),
        ),
      ],
    );
  }

  void _onDownloadPressed() {
    final DownloadRecord? downloadRecord = _controller.downloadRecord.value;
    if (downloadRecord != null) {
      // 先删除之前的下载
      _controller.removeDownload(downloadRecord.downloadId);
    }

    widget.upgrade.matchApkUrl().then((String apkUrl) {
      return _controller.commitDownload(
        version: widget.upgrade.androidVersion,
        url: apkUrl,
      );
    });
  }

  void _onInstallPressed() {
    final DownloadRecord? downloadRecord = _controller.downloadRecord.value;
    if (downloadRecord != null) {
      _controller
          .commitInstallation(
        downloadId: downloadRecord.downloadId,
        fromVersion: 'base',
        toVersion: widget.upgrade.androidVersion,
      )
          .catchError((dynamic error, StackTrace stackTrace) {
        print('error.toString()  ${error.toString()}');
        // AppToast.showFailure(error.toString());
      });
    }
  }
}
